function sta_start(){
    ps -fe|grep wpa_supplicant |grep -v grep
    if [ $? -ne 0 ]
    then  
        wpa_supplicant -Dnl80211 -i wlan0 -c /etc/wpa_supplicant.conf -B
        /sbin/udhcpc -b -i wlan0 -p /var/run/udhcpc.pid -R
        sleep 2s
        wpa_cli -i wlan0 enable_network 0
    fi
    wpa_cli status|grep COMPLETED
    if [ $? -eq 0 ]
    then
        #ps -fe|grep udhcpc_wlan |grep -v grep
        ipaddr=`ifconfig wlan0 | grep "inet addr" | cut -d ':' -f2 | awk '{print $1}'`
        if [ ! -n "$ipaddr" ]
        then
            pkill -15  udhcpc
            /sbin/udhcpc -b -i wlan0 -p /var/run/udhcpc.pid -R
        fi	
    fi
}
function hostap_start(){

    ps -fe|grep hostapd |grep -v grep
    if [ $? -ne 0 ]
    then  
        /usr/bin/hostapd /etc/hostapd.conf -B
        ps -fe|grep udhcpd |grep -v grep
        if [ $? -ne 0 ]
        then  
          /usr/sbin/udhcpd -f /etc/udhcpd.conf  &
        else
           pkill -15  udhcpd
            /usr/sbin/udhcpd -f /etc/udhcpd.conf  &
        fi
    fi
    ps -fe|grep udhcpd |grep -v grep
    if [ $? -ne 0 ]
    then  
        /usr/sbin/udhcpd -f /etc/udhcpd.conf  &
    fi
}
function hostap_stop()
{
    pkill -15  hostapd
    pkill -15  udhcpd

}



function ap_start(){
    apaddr=`ifconfig wlan1 | grep "inet addr" | cut -d ':' -f2 | awk '{print $1}'`
     if [ ! -n "$apaddr" ]
    then
        sh  /factory/script/config_ap_ssid.sh
        ifconfig wlan1 down
        ifconfig wlan1 192.168.122.1
        ifconfig wlan1 up
        sleep 1s
        hostap_start
    else
        hostap_start
    fi	
}

vs=`cat /home/Config/wlan.json | jq -r '.derail'`
if [[ $vs = 'on' ]];then
    echo 0 >/sys/class/gpio/gpio40/value
    type_wifi=`lsusb | grep "0bda:881a"`
    if [ ! -z "$type_wifi" ];then
        sta_start
        ap_start 
    fi
else
    echo 1 >/sys/class/gpio/gpio40/value
    hostap_stop
fi

exit 0;
#udhcpc -i wlan0 &
